package com.doubi.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.doubi.entity.*;
import com.doubi.service.*;
import com.doubi.entity.Commenttable;
import com.doubi.entity.Inform;
import com.doubi.entity.Userinfo;
import com.doubi.service.CommenttableService;
import com.doubi.service.InformService;
import com.doubi.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
@CrossOrigin("*")
public class CommenttableController {
    @Autowired
    private CommenttableService commenttableService;
    @Autowired
    private ReleasetableService releasetableService;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private InformService informService;


    @GetMapping("/myReleaseComment")
    public List<Commenttable> myReleaseComment(Integer userid) {
        //根据用户id查询用户作品集合
        QueryWrapper<Releasetable> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userid);
        List<Releasetable> releaseList = releasetableService.list(wrapper);
        //创建数组
        List<Integer> ridList = new ArrayList<Integer>();
        //获得用户作品id集合并添加到数组
        releaseList.forEach(releasetable -> {
            ridList.add(releasetable.getReleaseId());
        });
        //查询用户作品下所有评论
        List<Commenttable> commenttableList = commenttableService.getCommentByRid(ridList);
        //循环查询评论用户信息
        for (Commenttable comment : commenttableList) {
            QueryWrapper<Userinfo> qw=new QueryWrapper<>();
            qw.eq("userId", comment.getUserId());
            Userinfo one = userinfoService.getOne(qw);
            one.setHeadImg("http://192.168.43.92:9000/star/"+one.getHeadImg());
            //判断该用户是否是我的粉丝
            QueryWrapper<Friend> qw1=new QueryWrapper<>();
            qw1.eq("userId", one.getUserId()).and(i->i.eq("userFriend",userid)).and(i->i.eq("status",0));
            Friend friend = friendService.getOne(qw1);
            //对象不等于空说明此用户是我的粉丝
            if (friend!=null) {
                one.setIsFans(1);
            }else {
                one.setIsFans(0);
            }
            //查询评论是否是回复类型
            if (comment.getParentId()!=0){
                //查询回复的用户信息
                QueryWrapper<Userinfo> qw2=new QueryWrapper<>();
                QueryWrapper<Commenttable> qw3=new QueryWrapper<>();
                qw3.eq("cid", comment.getParentId());
                Commenttable byId = commenttableService.getOne(qw3);
                qw2.eq("userId", byId.getUserId());
                Userinfo one2 = userinfoService.getOne(qw2);//回复用户信息
                one2.setHeadImg("http://192.168.43.92:9000/star/"+one2.getHeadImg());
                comment.setBUserinfo(one2);
                //查询回复评论内容
                QueryWrapper<Commenttable> qw4=new QueryWrapper<>();
                qw4.eq("cid", comment.getParentId());
                Commenttable parentCommenttable = commenttableService.getOne(qw4);
                comment.setParentCommenttable(parentCommenttable);
            }
            //@
            if (comment.getCommentContent().indexOf("@")!=-1){
                QueryWrapper<Inform> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("informContent", comment.getCommentContent()).and(i->i.eq("buid",comment.getUserId()).and(j->j.eq("commentId",comment.getCid())));
                List<Inform> list=informService.list(queryWrapper);
                //判断此评论是否@多人
                if (list!=null&&list.size()>1){
                    List<Inform> isManyPeople = informService.getIsManyPeople(comment.getUserId(), list.get(0).getInformContent(), list.get(0).getInformTime(), list.get(0).getReleaseId());
                    if (isManyPeople.size()>1){
                        int atIndex=comment.getCommentContent().indexOf("@");//获得第一个@下标
                        for (int j=0;j<isManyPeople.size();j++){
                            QueryWrapper<Userinfo> qw4=new QueryWrapper<>();
                            qw4.eq("userId",isManyPeople.get(j).getUid());
                            Userinfo thisP=userinfoService.getOne(qw4);
                            StringBuffer msb=new StringBuffer(comment.getCommentContent());
                            msb.replace(atIndex,atIndex+1, "@"+thisP.getUserName()+" ");
                            comment.setCommentContent(msb.toString());
                            atIndex = comment.getCommentContent().substring(atIndex+1).indexOf("@")+atIndex+thisP.getUserName().length()-1;
                        }
                    }else {
                        StringBuffer sb=new StringBuffer(list.get(0).getInformContent());
                        sb.replace(list.get(0).getInformContent().indexOf("@"),list.get(0).getInformContent().indexOf("@")+1,"@"+list.get(0).getUserinfo().getUserName()+" ");
                        comment.setCommentContent(sb.toString());
                    }
                }
            }

            //存储用户信息
            comment.setUserinfo(one);
        }
        return commenttableList;
    }

    @GetMapping("/upvoteComment")
    public String upvoteComment(Integer cid,Integer userid) {
        //查询评论原来赞的数量
        QueryWrapper<Commenttable> wrapper = new QueryWrapper<>();
        wrapper.eq("cid", cid);
        Commenttable commenttable = commenttableService.getOne(wrapper);
        commenttable.setLikeCounts(commenttable.getLikeCounts()+1);
        boolean update = commenttableService.update(commenttable, wrapper);//赞+1
        //获得发出评论的用户id，并发送通知
        //先判断是否有同一评论点赞通知
        QueryWrapper<Inform> qw=new QueryWrapper<>();
        qw.eq("buid", userid).and(i->i.eq("uid",commenttable.getUserId()).and(j->j.eq("commentId",cid)));
        Inform i = informService.getOne(qw);
        if (i==null) {
            //说明没有通知
            Inform inform = new Inform();
            LocalDateTime now=LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String nowTime=now.format(formatter);
            inform.setInformTime(nowTime);
            inform.setReleaseId(commenttable.getReleaseId());
            inform.setCommentId(cid);
            inform.setInformType(0);
            inform.setUid(commenttable.getUserId());
            inform.setBuid(userid);
            boolean save = informService.save(inform);
            if (!save) {
                update=false;
            }
        }
        if (update){
            return "点赞成功";
        }else {
            return "点赞失败捏";
        }
    }

    /**
     * 取消对评论点赞方法
     * @param cid 评论id
     * @param userid 用户id
     * @return 取消结果
     */
    @GetMapping("/cancelUpvoteComment")
    public String cancelUpvoteComment(Integer cid,Integer userid) {
        //查询评论原来赞的数量
        QueryWrapper<Commenttable> wrapper = new QueryWrapper<>();
        wrapper.eq("cid", cid);
        Commenttable commenttable = commenttableService.getOne(wrapper);
        commenttable.setLikeCounts(commenttable.getLikeCounts()-1);
        boolean update = commenttableService.update(commenttable, wrapper);//赞-1
        if (update){
            return "取消点赞成功";
        }else {
            return "取消点赞失败捏";
        }
    }

    /**
     * 删除评论
     * @param cidList 要删除的评论id集合
     * @return
     */
    @PostMapping("/delComment")
    public String delComment(@RequestBody Map<String,Object> cidList) {
        List<Integer> list=(List<Integer>) cidList.get("cidList");
        int c = commenttableService.updateComment(list);
        int i = informService.updateInforms(list);
        if (i>0 && c>0){
            return "删除成功";
        }else {
            return "删除失败";
        }
    }

    @PostMapping("/sortComment")
    public List<Commenttable> sortComment(@RequestBody Map<String,Object> map) {
        List<Commenttable> list=(List<Commenttable>) map.get("list");
        String sortChoose=map.get("sortChoose").toString();
        List<Commenttable> newList=new ArrayList<>();
        for (Object o : list) {
            //将list转换成json字符串
            String jsonObject= JSON.toJSONString(o);
            //将json转换成需要的对象
            Commenttable c=JSON.parseObject(jsonObject,Commenttable.class);
            newList.add(c);
        }
        if (sortChoose.equals("最近发布")){
            newList.sort(Comparator.comparing(Commenttable::getCommentTime).reversed());
        }else if (sortChoose.equals("点赞最多")){
            newList.sort(Comparator.comparing(Commenttable::getLikeCounts).reversed());
        }
        return newList;
    }

    /**
     * 回复评论
     * @param
     * @return
     */
    @PostMapping("requestComment")
    public String requestComment(@RequestBody Map<String,Object> map) {
        Object obj=map.get("comment");
        //将obj数据转换成json字符串
        String jsonObject = JSON.toJSONString(obj);
        //将json转换成需要的对象
        Commenttable comment=JSON.parseObject(jsonObject,Commenttable.class);
        Integer uid=Integer.parseInt(map.get("userid").toString());
        //将回复评论存储
        int fasId=comment.getUserId();
        comment.setUserId(uid);
        comment.setParentId(comment.getCid());
        comment.setCid(0);
        comment.setLikeCounts(0);
        LocalDateTime now=LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String nowTime=now.format(formatter);
        comment.setCommentTime(nowTime);
        boolean save = commenttableService.save(comment);
        //通知
        Inform inform = new Inform();
        inform.setUid(fasId);
        inform.setBuid(comment.getUserId());
        inform.setInformContent(comment.getCommentContent());
        inform.setInformTime(nowTime);
        inform.setReleaseId(comment.getReleaseId());
        inform.setCommentId(commenttableService.getLastComment().getCid());
        inform.setInformType(1);
        boolean save1 = informService.save(inform);
        if (save1 && save){
            return "发送成功！";
        }else {
            return "发送失败！";
        }
    }
    /**
     * 发表评论
     */
    @PostMapping("addcommet")
    public Object addcomment(@RequestBody Commenttable commenttable) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date=formatter.format(now);
        //date.substring(5,10)
        commenttable.setCommentTime(date);
        commenttableService.save(commenttable);
        QueryWrapper<Commenttable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",commenttable.getUserId()).and(i->i.eq("commentTime",commenttable.getCommentTime())
                .and(j->j.eq("commentContent",commenttable.getCommentContent())));
        Commenttable one = commenttableService.getOne(queryWrapper);
        //存通知
        Inform inform=new Inform();
        inform.setInformContent(commenttable.getCommentContent());
        inform.setReleaseId(commenttable.getReleaseId());
        inform.setUid(commenttable.getUserId());
        inform.setBuid(commenttable.getBuid());
        inform.setCommentId(one.getCid());
        inform.setInformTime(date);
        inform.setInformType(1);
        return informService.save(inform);
    }
    /**
     * 回复评论
     */
    @PostMapping("addrply")
    public Object addrply(@RequestBody Commenttable commenttable) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String date=formatter.format(now);
        //date.substring(5,10)
        commenttable.setCommentTime(date);
        commenttable.setParentId(commenttable.getCid());
        commenttable.setCid(0);
        commenttableService.save(commenttable);
        QueryWrapper<Commenttable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",commenttable.getUserId()).and(i->i.eq("commentTime",commenttable.getCommentTime())
                .and(j->j.eq("commentContent",commenttable.getCommentContent())));
        Commenttable one = commenttableService.getOne(queryWrapper);
        //存通知
        Inform inform=new Inform();
        inform.setInformContent(commenttable.getCommentContent());
        inform.setReleaseId(commenttable.getReleaseId());
        inform.setUid(commenttable.getUserId());
        inform.setBuid(commenttable.getBuid());
        inform.setCommentId(one.getCid());
        inform.setInformTime(date);
        inform.setInformType(1);
        return informService.save(inform);
    }
    /**
     * 查询评论
     */
    @GetMapping("selectCommentList")
    public Object selectCommentList(Integer releaseId) {
        QueryWrapper<Commenttable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("releaseId", releaseId).orderByDesc("commentTime");
        List<Commenttable> list = commenttableService.list(queryWrapper);
        //存入要删除的对象
        List<Commenttable> removeCommentList = new ArrayList<>();
        for (Commenttable commenttable : list) {
            //查询用户信息
            commenttable.setUserinfo(getuserinfo(commenttable.getUserId()));
            //判断这条评论是不是某个人的评论
            QueryWrapper<Commenttable> c2=new QueryWrapper<>();
            c2.eq("parentId", commenttable.getCid());
            List<Commenttable> commenttableSon = commenttableService.list(c2);
            for (Commenttable son : commenttableSon) {
                son.setUserinfo(getuserinfo(son.getUserId()));
            }
            commenttable.setChildren(commenttableSon);
            if(commenttable.getParentId()!=0){
                removeCommentList.add(commenttable);
            }
        }
        //删除对象
        if (removeCommentList.size() > 0) {
            for (Commenttable commenttable : removeCommentList) {
                list.remove(commenttable);
            }
        }
        return list;
    }
    /**
     * 查询用户信息
     */
    private Userinfo getuserinfo(Integer userId) {
        QueryWrapper<Userinfo> userinfoQueryWrapper = new QueryWrapper<>();
        userinfoQueryWrapper.eq("userId", userId);
        Userinfo userinfo = userinfoService.getOne(userinfoQueryWrapper);
        userinfo.setHeadImg("http://localhost:9000/star/"+userinfo.getHeadImg());
        return userinfo;
    };
    /**
     * 点赞评论
     */
    @PostMapping("addComment")
    public Object addComment(@RequestBody Commenttable commenttable) {
        commenttable.setLikeCounts(commenttable.getLikeCounts()+1);
        return commenttableService.updateLikeComment(commenttable);
    }
    /**
     * 取消点赞
     */
    @PostMapping("jianComment")
    public Object jianComment(@RequestBody Commenttable commenttable) {
        commenttable.setLikeCounts(commenttable.getLikeCounts()-1);
        return commenttableService.updateLikeComment(commenttable);
    }
}
